package fr.labri.macchiato.client.cart;

import java.util.ArrayList;
import java.util.List;

import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.fields.CheckboxItem;

import fr.labri.macchiato.client.cart.events.ValidateSearchHandler;
import fr.labri.macchiato.framework.business.finder.Callback;
import fr.labri.macchiato.framework.business.model.product.Model;

/**
 * A widget searching for model corresponding to an article name
 * 
 * @author Paul SARRAUTE
 *
 */
public class ModelSearch extends ProductSearch {

	private CheckboxItem[] modelItems;
	
	private List<Model> resultModels;

	/**
	 * Create the widget searching for model with the specified keyword
	 * 
	 * @param articleName The keyword used for the search
	 */
	ModelSearch(String articleName) {
		super(articleName);
		
		resultModels = null;
	}

	

	private void addModels(List<Model> models) {
		resultModels = models;
		
		resultNumber.setContents(resultModels.size() + " élément(s) trouvé(s)");
		
		modelItems = new CheckboxItem[models.size()];
		int index = 0;

		for (Model model : models) {
			CheckboxItem modelCheckBox = new CheckboxItem(model.getEan(),
					model.getName());
			modelItems[index++] = modelCheckBox;
		}
		contents.setFields(modelItems);
		
		displayContents();
	}



	@Override
	void addValidateHandler(final ValidateSearchHandler handler) {
		validButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				List<Model> selectedModels = getSelectedModels();

				handler.setSelectedModels(selectedModels);
				handler.fireEvent();

			}

		});
	}

	/**
	 * @return The models selected by the user
	 */
	private List<Model> getSelectedModels() {
		List<Model> models = new ArrayList<Model>();
		
		for (int i = 0; i < modelItems.length; i++) {
			if (modelItems[i].getValueAsBoolean())
				for (Model m : resultModels) {
					if (m.getEan().equals(modelItems[i].getName())) {
						models.add(m);
						break;
					}
				}
		}
		return models;
	}



	@Override
	void startSearch() {
		if (resultModels == null) {
			progressbar = new ProgressLabel("Recherche en cours...");
			addMember(progressbar);
			getProductFinder().getModels(searchKeyword,
					new Callback<List<Model>>() {

						@Override
						public void onCallback(List<Model> result) {
							addModels(result);
						}
					});
		} else {
			show();
		}
		
	}
}
